<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.menu_name" placeholder="菜单名称" clearable class="filter-item" style="width: 200px;" />
      <el-button class="filter-item search" icon="el-icon-search" @click="handleSearch">
        搜索
      </el-button>
      <el-button class="filter-item" icon="el-icon-refresh" @click="handleRefresh">
        重置
      </el-button>
      <el-button class="filter-item fr" type="primary" icon="el-icon-plus" @click="handleCreateTop">
        新增
      </el-button>
    </div>
    <el-table :data="list" style="width: 100%;margin-bottom: 20px;" row-key="id" border default-expand-all :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column prop="menu_name" label="菜单名称" width="200" />
      <el-table-column prop="route" label="路由Path" width="200" />
      <el-table-column prop="menu_mark" label="权限标识" width="200" />
      <el-table-column label="可操作权限" width="400">
        <template slot-scope="permission">
          <el-popover v-for="(action, index) in permission.row.actionList" :key="index" placement="top" width="180"
            title="操作">
            <p>权限标识: {{ action.menu_name }}</p>
            <div style="margin: 0;width: 200px">
              <el-button size="mini" icon="el-icon-delete" type="danger" @click="handleDelete(action.id)">删除</el-button>
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="handleUpdate(beforeHandleUpdate(action))">编辑</el-button>
            </div>
            <el-tag slot="reference" style="margin-right: 2px;" size="mini">{{ action.menu_name }}</el-tag>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="200">
        <template slot-scope="permission">
          <el-switch v-model="permission.row.hidden" active-text="启用" inactive-text="禁用" :active-value="1"
            :inactive-value="2" @change="disOrEnablePermission(permission.row)" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="200">
        <template slot-scope="{row}">
          <span>{{ row.create_time|formatDate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="200">
        <template slot-scope="permission">
          <el-button size="small" type="primary" icon="el-icon-plus" @click="beforeHandleCreate(permission.row)"/>
          <el-button size="small" type="primary" icon="el-icon-edit" @click="isButton=false;handleUpdate(permission.row)" />
          <el-button size="small" type="danger" icon="el-icon-delete" @click="handleDelete(permission.row.id)" />
        </template>

      </el-table-column>
    </el-table>


    <!------------------------------------------------- 菜单表单 ----------------------- ------------------------------>
    <el-dialog :title="title" :visible.sync="formVisible" @close="handleCancel">
      <el-form :ref="formName" :model="formFieldsData" :rules="rules">
        <el-form-item v-if="showType" label="菜单名称" :label-width="formLabelWidth" prop="type">
          <el-radio-group v-model="formFieldsData.type" prop="type" @change="handleTypeChange">
            <el-radio-button label="1">菜单</el-radio-button>
            <el-radio-button label="2">按钮</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="菜单名称" :label-width="formLabelWidth" prop="menu_name">
              <el-input v-model="formFieldsData.menu_name" placeholder="请输入菜单名称" autocomplete="off" clearable />
            </el-form-item>
            <el-form-item v-if="!isButton" label="模块" :label-width="formLabelWidth" prop="module">
              <el-input v-model="formFieldsData.module" placeholder="请输入模块" autocomplete="off" clearable />
            </el-form-item>
            <el-form-item v-if="!isButton" label="菜单Path" :label-width="formLabelWidth" prop="route">
              <el-input v-model="formFieldsData.route" placeholder="请输入菜单Path" autocomplete="off" clearable />
            </el-form-item>
            <el-form-item v-if="!isButton" label="Redirect" :label-width="formLabelWidth" prop="redirect">
              <el-input v-model="formFieldsData.redirect" placeholder="请输入Redirect" autocomplete="off" clearable />
            </el-form-item>
            <el-form-item v-if="!isButton" label="keepalive" :label-width="formLabelWidth" prop="keepalive">
              <el-radio v-model="formFieldsData.keepalive" :label="1" checked>启用</el-radio>
              <el-radio v-model="formFieldsData.keepalive" :label="2">禁用</el-radio>
            </el-form-item>
            <el-form-item v-if="isButton" label="排序" :label-width="formLabelWidth" prop="sort">
              <el-input-number v-model="formFieldsData.sort" :min="1" :max="100000" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="isButton" label="权限标识" :label-width="formLabelWidth" prop="menu_mark">
              <template><span>{{ permissionPrefix }}@</span></template>
              <el-select v-model="formFieldsData.menu_mark" placeholder="请选择方法">
                <el-option v-for="item in methods" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item v-else label="权限标识" :label-width="formLabelWidth" prop="menu_mark">
              <el-input v-model="formFieldsData.menu_mark" placeholder="请输入权限标识(controller@action)" autocomplete="off"
                clearable />
            </el-form-item>
            <el-form-item v-if="!isButton" label="菜单 Icon" :label-width="formLabelWidth" prop="icon">
              <el-input v-model="formFieldsData.icon" placeholder="请选择菜单Icon" clearable @input="selectIcon" />
            </el-form-item>
            <el-form-item v-if="!isButton" label="组件" :label-width="formLabelWidth" prop="component">
              <el-select v-model="formFieldsData.component" filterable placeholder="请选择组件">
                <el-option v-for="(item, key) in components" :key="key" :value="key" :label="key" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="!isButton" label="排序" :label-width="formLabelWidth" prop="sort">
              <el-input-number v-model="formFieldsData.sort" :min="1" :max="100000" />
            </el-form-item>
            <el-form-item v-if="!isButton" label="hidden" :label-width="formLabelWidth">
              <el-radio v-model="formFieldsData.hidden" :label="1" checked>显示</el-radio>
              <el-radio v-model="formFieldsData.hidden" :label="2">隐藏</el-radio>
            </el-form-item>
          </el-col>
        </el-row>
        <el-input v-model="formFieldsData.pid" type="hidden" />
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="选择菜单图标" :visible.sync="iconVisable" width="70%">
      <icons @selectIcon="handleSelectIcon" />
    </el-dialog>
  </div>
</template>

<script>
  import {
    create,
    update,
    deleteRecord,
    getList
  } from '@/api/menu'
  import store from '@/store'
  import icons from './icons/index'
  import {
    formatDate
  } from '@/utils/formatDate.js'
  import waves from '@/directive/waves' // waves directive
  import componentsMap from '@/config/componentsMap'
  import {
    parseTime
  } from '@/utils'
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  export default {
    name: 'Index',
    components: {
      icons
    },
    filters: {
      formatDate(time) {
        time = time * 1000
        let date = new Date(time)

        return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
      }
    },
    data() {
      return {
        title: '新增',
        formName: 'rules',
        formLabelWidth: '120px',
        isButton: false,
        iconVisable: false,
        formVisible: false,
        showType: false,
        components: componentsMap,
        list: [],
        listQuery: {
          menu_name: '',
        },
        // 表单数据
        formFieldsData: {
          menu_name: '',
          menu_mark: '',
          module: '',
          icon: '',
          route: '',
          component: '',
          redirect: '',
          sort: 1,
          keepalive: 1,
          hidden: 1,
          type: 1 // 菜单
        },
        // 验证规则
        rules: {
          permission_name: [{
              required: true,
              message: '请输入菜单名称',
              trigger: 'blur'
            },
            {
              max: 10,
              message: '最大支持 10 个字符',
              trigger: 'blur'
            }
          ],
          permission_mark: [{
              required: true,
              message: '请输入权限标识',
              trigger: 'blur'
            },
            {
              max: 50,
              message: '最大支持 50 个字符',
              trigger: 'blur'
            }
          ],
          module: [{
              required: true,
              message: '请输入模块',
              trigger: 'blur'
            },
            {
              max: 20,
              message: '最大支持 20 个字符',
              trigger: 'blur'
            }
          ],
          route: [{
              required: true,
              message: '请输入菜单路由',
              trigger: 'blur'
            },
            {
              max: 50,
              message: '最大支持 50 个字符',
              trigger: 'blur'
            }
          ]
        },
      }
    },
    created() {
      this.getList()
    },
    methods: {
      getList(params = null) {
        const query = params ? params : this.queryParam
        getList(this.listQuery).then(response => {
          this.list = response.data
        })
      },
      selectIcon() {
        this.iconVisable = true
      },
      // 选择菜单图标
      handleSelectIcon(item) {
        this.formFieldsData.icon = item
        this.iconVisable = false
      },
      // 关闭
      handleCancel() {
        this.formVisible = false
        // 防止提交关闭的时候 导致数据清空 所以延迟 300ms 清空数据
        setTimeout(this.resetFormFields, 300)
        this.$refs[this.formName].clearValidate()
        if (this.afterCancel !== undefined) {
          this.afterCancel()
        }
      },
      handleCreateTop() {
        this.isButton = false
        this.formFieldsData.parent_id = 0
        this.formFieldsData.type = 1 // 菜单类型
        this.showType = false
        this.handleCreate()
      },
      // 弹出层
      handleCreate() {
        this.title = '新增'
        this.id = null
        // 创建前
        if (this.beforeCreate !== undefined) {
          this.beforeCreate()
        }
        this.formVisible = true
      },
      beforeHandleCreate(permission = null) {
        this.handleCreate()
        if (permission.parent_id > 0) {
          this.permissionPrefix = permission.menu_mark.indexOf('@') === -1 ? permission.menu_mark : permission.menu_mark
            .split('@')[0]
          this.isButton = true
          this.formFieldsData.type = 2 // 按钮
          this.showType = true
          this.getMethods(permission.id)
        } else {
          this.isButton = false
          this.showType = true
          this.formFieldsData.type = 1 // 按钮
        }
        this.formFieldsData.parent_id = permission.id
        this.title = this.title.concat(' [', permission.menu_name, ']')
      },
      // 更新
      handleUpdate(record, col, idx) {
        console.log(record)
        this.title = '更新'
        this.id = record[this.pk !== undefined ? this.pk : 'id']
        // 更新前
        if (this.beforeUpdate !== undefined) {
          this.beforeUpdate(record)
        }
        Object.keys(this.formFieldsData).forEach((k) => {
          this.formFieldsData[k] = record[k]
        })
        console.log(this.formFieldsData)
        this.formVisible = true
      },
      disOrEnablePermission(permission) {
    var data = {};
    data['id'] = permission.id;
    data['hidden'] = permission.hidden;
data['menu_name'] = permission.menu_name;
         update(data).then(res => {
           this.$message.success(res.msg)
            this.handleUpdateUserInfo()
           this.handleSearch()
           this.getList()
         })

      },
    handleUpdateUserInfo() {
      store.dispatch('user/getInfo').then(response => {
        const { roles, permissions } = response
        store.dispatch('permission/generateRoutes', [roles, permissions]).then(r => {})
      })
    },
      // 删除
      handleDelete(id) {
        // 更新前
        if (this.beforeDelete !== undefined) {
          this.beforeDelete()
        }
        deleteRecord(id).then(resp=>{
              this.$notify({
                title: 'Success',
                message: 'Update Successfully',
                type: 'success',
                duration: 2000,
                onclose: this.getList()
              })
              this.handleUpdateUserInfo()
        })
      },
      handleSearch() {
        this.listQuery.page = 1
        this.getList()
      },
      handleRefresh() {
        this.listQuery.menu_name = null
        this.getList()
      },
      // 切换type
      handleTypeChange(value) {
        this.isButton = parseInt(value) === 2
      },
      beforeHandleUpdate(action) {
        this.isButton = true // 按钮
        this.showType = true // 按钮
        this.permissionPrefix = action.menu_mark.indexOf('@') === -1 ? action.menu_mark : action.menu_mark
          .split('@')[0]
        action.menu_mark = action.menu_mark.split('@')[1]

        return action
      },
      handleSubmit() {
        if (this.beforeSubmit !== undefined) {
          this.beforeSubmit()
        }
        console.log(this.formFieldsData);
        this.$refs[this.formName].validate((valid) => {
          if (valid) {
            if (!this.id) {
              create(this.formFieldsData).then(resp => {
                this.formVisible = false
                this.handleRefresh()
                this.resetFormFields()
                this.getList()
              })

            } else {
              this.formFieldsData.id=this.id
              update(this.formFieldsData).then(resp => {
                this.formVisible = false
                this.handleRefresh()
                this.resetFormFields()
                this.getList()
                this.handleUpdateUserInfo()
              })
            }
          } else {
            return false
          }
        })
        this.handleRefresh()
      },

      resetFormFields() {
        Object.keys(this.formFieldsData).forEach((k) => {
          switch (typeof this.formFieldsData[k]) {
            case 'object':
              this.formFieldsData[k] = []
              break
            case 'bigint':
              this.formFieldsData[k] = 1
              break
            case 'number':
              if (k === 'parent_id' || k === 'pid') {
                this.formFieldsData[k] = 0
              } else {
                this.formFieldsData[k] = 1
              }
              break
            case 'string':
              this.formFieldsData[k] = ''
              break
            default:
              break

              // eslint-disable-next-line no-unreachable
              if (this.formFieldsDefaultValues !== undefined && this.formFieldsDefaultValues.indexOf(k)) {
                this.formFieldsData[k] = this.formFieldsDefaultValues[k]
              }
          }
        })
      },
    }
  }
</script>

<style>
</style>
